package routing;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import config.RabbitMqConnection;
import org.junit.Test;

/**
 * @description: 消息发布者（提供者）,Routing 模式，需要指定 routingKey 一个 exchange 对应多个 queue，queue 又对应多个 consumer
 * @author:刘腾辉
 * @create:2020/10/20 9:38
 */
public class Provider {
    @Test
    public void Publish() throws Exception {

        /**
         * 1.获取连接
         */
        Connection rabbitMqConnection = RabbitMqConnection.getRabbitMqConnection();

        /**
         * 2.创建 channel
         */
        Channel channel = rabbitMqConnection.createChannel();

        /**
         * 3.创建交换机 exchange 并将队列与交换机绑定
         * 绑定可以在订阅端也可以在发布端
         */
        channel.exchangeDeclare("routing-exchange-direct", BuiltinExchangeType.DIRECT);
        channel.queueBind("routing queue one", "routing-exchange-direct", "ERROR");
        channel.queueBind("routing queue two", "routing-exchange-direct", "INFO");

        /**
         * 4.发布消息到 exchange
         */
        String error = "ERROR 消息的 routingKey";
        String info = "INFO 消息的 routingKey";
        channel.basicPublish("routing-exchange-direct","ERROR",null,error.getBytes());
        channel.basicPublish("routing-exchange-direct","INFO",null,info.getBytes());
        channel.basicPublish("routing-exchange-direct","INFO",null,info.getBytes());
        channel.basicPublish("routing-exchange-direct","INFO",null,info.getBytes());

        /**
         * 4.关闭资源
         */
        System.out.println("生产者消息发布完毕!");
        channel.close();
        rabbitMqConnection.close();
    }
}
